package furns.web;

import furns.entity.Cart;
import furns.entity.Member;
import furns.entity.Order;
import furns.service.OrderService;
import furns.service.impl.OrderServiceImpl;
import furns.utils.JDBCUtilsByDruid;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class OrderServlet extends BasicServlet{
    private OrderService orderService = new OrderServiceImpl();

    protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编写业务
        //当进行结算的时候，判断用户是否登录，如果没有登录，就跳转到登录界面，如果登录就进行结算
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");

        //如果cart == null , 说明会员没有购买任何家居, 转发到首页,防止空订单
        //需要补充一个逻辑, 购物车在sessoin, 但是没有家居数据
        if (cart == null || cart.isEmpty()){
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
            return;
        }

        //获取当前登录的memberId
        Member member = (Member)session.getAttribute("member");
        if (member == null){
            //没有登录，转发到登录界面
            req.getRequestDispatcher("/views/member/login.jsp").forward(req,resp);
            return;
        }

        //登录成功,进行结算,生成订单
        //1. 如果只是希望对orderService.saveOrder()进行事务控制
        //2. 可以不使用过滤器, 直接在这个位置，进行提交和回滚即可
//        String orderId = null;
//        try {
//            orderId = orderService.saveOrder(member.getId(), cart);
//            JDBCUtilsByDruid.commit(); //提交
//        } catch (Exception e) {
//            JDBCUtilsByDruid.rollback();
//            e.printStackTrace();
//        }

        String orderId = orderService.saveOrder(member.getId(), cart);
        session.setAttribute("orderId",orderId);
        //转发
        resp.sendRedirect(req.getContextPath() + "/views/order/checkout.jsp");
    }
}
